package com.umeox.watch.moto.chat.ui

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.telephony.TelephonyManager
import android.util.Log
import android.view.View
import android.widget.ImageView
import com.google.android.cameraview.CameraView
import com.umeox.moto.common.utils.FileUtils
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity
import com.umeox.watch.moto.chat.R
import com.umeox.watch.moto.chat.db.ContactInfo
import com.umeox.watch.moto.chat.utils.Constants
import com.umeox.watch.moto.chat.utils.ImageUtil


class TakePhotoActivity : ThemeAppCompatActivity() {

    companion object {
        private const val TAG = "TakePhotoActivity"
        private const val STATE_INIT = 0
    }


    var path: String? = null
    var picUri: Uri? = null
    private lateinit var mCallReceiver: BroadcastReceiver
    private lateinit var mCameraPreview: CameraView
    private lateinit var mTakePhoto: ImageView
    private lateinit var mSendPhoto: ImageView
    private val state = STATE_INIT

    private lateinit var mSwitchBtn: View
    private var mMediaPlayer: MediaPlayer? =null
    private var mBgHandler: Handler? = null

    @SuppressLint("WrongConstant")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val mContact: ContactInfo? = intent.getParcelableExtra(Constants.EXTRA_CONTACT)
        if (mContact == null) {
            finish()
            return
        }
        path = FileUtils.getChatsCacheDir(mContact.friendId)
        setContentView(R.layout.act_camera)
        mCameraPreview = findViewById(R.id.camera_view)
        mCameraPreview.setTakePictureAutoPreview(false)
        mTakePhoto = findViewById(R.id.ibTakePhoto)
        mSendPhoto = findViewById(R.id.ivSendPhoto)
        mSwitchBtn = findViewById(R.id.camera_switch_button)
        mTakePhoto.setOnClickListener { view: View? -> takePhoto(view) }
        mSendPhoto.setOnClickListener { setResult() }
        mSwitchBtn.visibility = View.GONE
        mSwitchBtn.setOnClickListener { mCameraPreview.switchCameraFacing() }
        mCameraPreview.addCallback(mCallback)

        mCallReceiver = object : BroadcastReceiver() {
            //如果有电话或者视频电话进来，停止正在播放的语聊
            override fun onReceive(context: Context, intent: Intent) {
                val action = intent.action
                when {
                    Constants.ACTION_INCOMING_CALL.equals(action, true) -> {
                        val telephony =
                            context.getSystemService(TELEPHONY_SERVICE) as TelephonyManager
                        if (telephony.callState == TelephonyManager.CALL_STATE_RINGING) {
                            onBackPressed()
                        }
                    }
                    Constants.ACTION_RINGING_VIDEO_CALL.equals(action, true) -> {
                        onBackPressed()
                    }
                }
            }
        }
        val intentFilter = IntentFilter()
        intentFilter.addAction(Constants.ACTION_INCOMING_CALL)
        intentFilter.addAction(Constants.ACTION_RINGING_VIDEO_CALL)
        registerReceiver(mCallReceiver, intentFilter)
    }

    private fun takePhoto(view: View?) {
        mCameraPreview.takePicture()
        mTakePhoto.isEnabled = false
    }

    private fun setResult() {
        val data = Intent()
        data.putExtra(Constants.EXTRA_PICTURE_URI, picUri)
        setResult(RESULT_OK, data)
        finish()
    }

    private fun deleteFile() {
        if (picUri != null) {
            getBgHandler().post {
                contentResolver.delete(picUri!!, null, null)
                picUri = null
            }
        }
    }

    private val mCallback: CameraView.Callback = object : CameraView.Callback() {
        override fun onPictureTaken(cameraView: CameraView?, data: ByteArray?) {
            super.onPictureTaken(cameraView, data)
            getBgHandler().post {
                picUri = ImageUtil.saveImageFile(this@TakePhotoActivity, path, data,mCameraPreview.facing == CameraView.FACING_FRONT)
                runOnUiThread { showSendPictureButton() }
            }
        }

        override fun onShutter() {
            super.onShutter()
            playRingtone()
        }
    }

    private fun showSendPictureButton() {
        mTakePhoto.visibility = View.GONE
        mSwitchBtn.visibility = View.GONE
        mSendPhoto.visibility = View.VISIBLE
    }

    fun playRingtone() {
        releaseMediaPlayer()
        mMediaPlayer = MediaPlayer.create(this, R.raw.camera)
        mMediaPlayer?.start()
    }

    private fun releaseMediaPlayer() {
        if(mMediaPlayer != null){
            mMediaPlayer?.stop()
            mMediaPlayer?.release()
        }
    }

    private fun getBgHandler(): Handler {
        if (mBgHandler == null) {
            val handlerThread = HandlerThread("background")
            handlerThread.start()
            mBgHandler = Handler(handlerThread.looper)
        }
        return mBgHandler as Handler
    }

    override fun onBackPressed() {
        deleteFile()
        finish()
    }

    override fun onResume() {
        super.onResume()
        if (mTakePhoto.isEnabled) {
            mCameraPreview.start()
        }
    }

    override fun onPause() {
        super.onPause()
        mCameraPreview.stop()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mBgHandler != null) {
            mBgHandler?.looper?.quitSafely()
            mBgHandler = null
        }

        try {
            mCameraPreview.stop()
            unregisterReceiver(mCallReceiver)
        } catch (e: Exception) {
            Log.d(TAG, "onDestroy: ", e)
        }
    }
}